package com.ms.education.order.controller;

import com.ms.education.JwtUtils;
import com.ms.education.R;
import com.ms.education.exceptionHandler.EduException;
import com.ms.education.order.service.PayLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 * 支付日志表 前端控制器
 * </p>
 *
 * @author ms
 * @since 2023-02-16
 */
@RestController
@RequestMapping("/order/pay-log")
public class PayLogController {

    @Autowired
    private PayLogService payLogService;

    //生成微信支付二维码接口
    @GetMapping("createNative/{orderNo}")
    public R createNative(@PathVariable String orderNo) {
        Map map = payLogService.createNative(orderNo);
        return R.ok().data(map);
    }

    //查询订单状态
    @Transactional
    @GetMapping("/queryPayStatus/{orderNo}/{courseId}")
    public R queryPayStatus(@PathVariable String orderNo,
                            @PathVariable("courseId") Integer courseId) {
        //调用查询接口
        Map<String, String> map = payLogService.queryPayStatus(orderNo);
        if (map == null) {//出错
            throw new EduException(20001, "支付出错");
        }
        if (map.get("trade_state").equals("SUCCESS")) {//如果成功
            //更改订单状态
            payLogService.updateOrderStatus(map, courseId);
            return R.ok().message("支付成功");
        }
        return R.ok().code(25000).message("支付中");
    }

    @Transactional
    @GetMapping("queryPayStatusByClassId/{orderNo}/{classId}")
    public R queryPayStatusByClassId(@PathVariable String orderNo,
                                     @PathVariable("classId") Integer classId) {
        //调用查询接口
        Map<String, String> map = payLogService.queryPayStatus(orderNo);
        if (map == null) {//出错
            throw new EduException(20001, "支付出错");
        }
        if (map.get("trade_state").equals("SUCCESS")) {//如果成功
            //更改订单状态
            payLogService.updateOrderStatusByClassId(map, classId);
            return R.ok().message("支付成功");
        }
        return R.ok().code(25000).message("支付中");

    }

}
